package com.bjpowernode.common.client;

import com.bjpowernode.mvc.model.dto.user.HeaderImageDTO;
import com.bjpowernode.mvc.model.dto.user.SaveHeaderImageDTO;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.springframework.stereotype.Component;

import java.io.IOException;



public class FastDfsClient {

    public void init() throws MyException, IOException {
        ClientGlobal.init("fdfs_client.conf");
    }


    //获取StorageClient
    public StorageClient getStorageClient() throws IOException, MyException {

        //创建TrackServer,StorageServer对象
        TrackerServer trackerServer = null;
        StorageServer storageServer = null;


        //创建TrackClient对象,负责连接到tracker
        TrackerClient trackerClient = new TrackerClient();
        trackerServer = trackerClient.getTrackerServer();
        storageServer = trackerClient.getStoreStorage(trackerServer);


        //创建storageClient对象,负责上传,下载等操作
        StorageClient storageClient = new StorageClient(trackerServer, storageServer);


        return storageClient;

    }


    //上传文件.
    public SaveHeaderImageDTO uploadFile(HeaderImageDTO dto) {
        SaveHeaderImageDTO resultDto = null;
        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();

            NameValuePair meta[] = {
                    new NameValuePair("size", String.valueOf(dto.getSize())),
                    new NameValuePair("width", String.valueOf(dto.getWidth())),
                    new NameValuePair("height", String.valueOf(dto.getHeight())),
                    new NameValuePair("ext", dto.getExtName()),
            };

            String[] strings = storageClient.upload_file(dto.getContent(), dto.getExtName(), meta);

            if (strings != null && strings.length == 2){
                resultDto=new SaveHeaderImageDTO();
                resultDto.setGroup(strings[0]);
                resultDto.setFileId(strings[1]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                storageClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return resultDto;
    }


    //删除文件.
    public boolean deleteFastDfs(String group, String fileId) {

        boolean delete = false;

        StorageClient storageClient = null;
        try {
            storageClient = getStorageClient();
            int i = storageClient.delete_file(group, fileId);
            delete = (i == 0);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                storageClient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return delete;
    }


}
